package com.ruoyi.business.service.impl;

import java.util.*;
import java.util.stream.Collectors;

import com.ruoyi.business.domain.*;
import com.ruoyi.business.service.IContentService;
import com.ruoyi.business.service.IDepartService;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.uuid.IdWorker;
import com.ruoyi.system.service.ISysDictDataService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.business.mapper.StatisticsMapper;
import com.ruoyi.business.service.IStatisticsService;

import javax.annotation.Resource;

/**
 * StatisticsService业务层处理
 *
 * @author win
 * @date 2021-06-24
 */
@Service
public class StatisticsServiceImpl implements IStatisticsService {
    @Autowired
    private StatisticsMapper statisticsMapper;

    @Resource
    private IdWorker idWorker;

    @Resource
    private ISysDictDataService dictDataService;

    @Resource
    private IContentService contentService;

    @Resource
    private IDepartService departService;

    /**
     * 查询Statistics
     *
     * @param id StatisticsID
     * @return Statistics
     */
    @Override
    public List<StatisticsVO> selectStatisticsById(Long id) {
        List<StatisticsVO> statisticsVOS = statisticsMapper.selectStatisticsById(id);

        SysDictData sysDictData = new SysDictData();
        sysDictData.setDictType("business_belong");
        List<SysDictData> belongList = dictDataService.selectDictDataList(sysDictData);

        statisticsVOS.forEach(item -> {
            for (SysDictData dictData : belongList) {
                if (item.getContentBelong() != null && item.getContentBelong().toString().equals(dictData.getDictValue())) {
                    item.setContentBelongName(dictData.getDictLabel());
                }
                if (item.getStaffBelong() != null && item.getStaffBelong().toString().equals(dictData.getDictValue())) {
                    item.setStaffBelongName(dictData.getDictLabel());
                }
            }
        });

        return statisticsVOS;
    }

    /**
     * 查询Statistics列表
     *
     * @param statistics Statistics
     * @return Statistics
     */
    @Override
    public List<Content> selectStatisticsList(Statistics statistics) {
        SysDictData sysDictData = new SysDictData();
        sysDictData.setDictType("business_belong");
        List<SysDictData> belongList = dictDataService.selectDictDataList(sysDictData);

        List<Content> contents = statisticsMapper.selectStatisticsList(statistics);

        contents.forEach(item -> {
            for (SysDictData dictData : belongList) {
                if (item.getBelong().toString().equals(dictData.getDictValue())) {
                    item.setBelongName(dictData.getDictLabel());
                }
            }
        });

        return contents;
    }

    /**
     * 新增Statistics
     *
     * @param statistics Statistics
     * @return 结果
     */
    @Override
    public int insertStatistics(Statistics statistics) {
        statistics.setId(idWorker.nextId());
        statistics.setCreateTime(DateUtils.getNowDate());
        return statisticsMapper.insertStatistics(statistics);
    }

    /**
     * 修改Statistics
     *
     * @param statistics Statistics
     * @return 结果
     */
    @Override
    public int updateStatistics(Statistics statistics) {
        statistics.setUpdateTime(DateUtils.getNowDate());
        return statisticsMapper.updateStatistics(statistics);
    }

    /**
     * 批量删除Statistics
     *
     * @param ids 需要删除的StatisticsID
     * @return 结果
     */
    @Override
    public int deleteStatisticsByIds(Long[] ids) {
        return statisticsMapper.deleteStatisticsByIds(ids);
    }

    /**
     * 删除Statistics信息
     *
     * @param id StatisticsID
     * @return 结果
     */
    @Override
    public int deleteStatisticsById(Long id) {
        return statisticsMapper.deleteStatisticsById(id);
    }

    /**
     * 查询该ip查看的文章今天是否进行了统计
     *
     * @param contentId
     * @param clientIp
     * @return
     */
    @Override
    public boolean hasTodayStatistics(Long contentId, String clientIp) {
        Date todayStartTime = DateUtils.getTodayStartTime();
        Date todayEndTime = DateUtils.getTodayEndTime();
        int num = statisticsMapper.hasTodayStatistics(contentId, clientIp, todayStartTime, todayEndTime);
        return num > 0;
    }

    /**
     * 部门发布统计
     *
     * @return
     */
    @Override
    public List<DepartVO> departPublishStatistics() {
        SysDictData sysDictData = new SysDictData();
        sysDictData.setDictType("business_belong");
        List<SysDictData> belongList = dictDataService.selectDictDataList(sysDictData);

        List<Depart> departs = selectDepartPublish();

        return belongList.stream().map(item -> {
            DepartVO departVO = new DepartVO();
            departVO.setBelong(item.getDictCode());
            departVO.setBelongName(item.getDictLabel());

            List<Depart> target = departs.stream().filter(depart -> depart.getBelong().equals(item.getDictCode())).collect(Collectors.toList());
            departVO.setDepartList(target);
            return departVO;
        }).collect(Collectors.toList());
    }

    /**
     * todo  热点排行  只取前5，且没有详情页
     * todo  点击排行  可以显示多条，且有详情页
     *
     * todo  人员部分 归属及部门 的树选择
     * todo  管理端 统计部分及导出详情
     *
     * @return
     */
    @Override
    public List<Depart> selectDepartStatistics(Integer limit, Integer belong){
        return statisticsMapper.selectStatisticsWithLimit(limit, belong);
    }

    @Override
    public List<Content> selectContentStatistics(Integer limit){
        return statisticsMapper.selectContentStatisticsWithLimit(limit);
    }

    @Override
    public List<Content> selectContentStatisticsPage(){
        return statisticsMapper.selectContentStatisticsWithPage();
    }


    /**
     * 根据部门id获取各个部门发稿的记录
     * @return
     */
    @Override
    public List<Content> selectContentsByDepartId(Long departId){
        List<Content> contentIds = statisticsMapper.selectContentIdsByDepartId(departId);

        return contentIds.stream().peek(item -> {
            Content content = contentService.selectContentById(item.getId());
            item.setTitle(content.getTitle());
            item.setCreateTime(content.getCreateTime());
            item.setType(content.getType());

            Depart depart = departService.selectDepartById(content.getDepartId());
            item.setDepartName(depart != null ? depart.getName() : "");

        }).collect(Collectors.toList());
    }

    /**
     * 获取某部门发布文章的信息
     * @return
     */
    @Override
    public List<Depart> selectDepartPublish() {
        return statisticsMapper.selectDepartPublish();
    }

    @Override
    public List<PublishVo> selectPublishStatistics() {

        List<Depart> departs = statisticsMapper.selectDepartPublish();

        SysDictData sysDictData = new SysDictData();
        sysDictData.setDictType("business_belong");
        List<SysDictData> belongList = dictDataService.selectDictDataList(sysDictData);

        ArrayList<PublishVo> publishVos = new ArrayList<>();

        Map<Long, List<Depart>> collect = departs.stream().collect(Collectors.groupingBy(Depart::getBelong));

        collect.forEach((key, value) -> {

            PublishVo publishVo = new PublishVo();
            publishVo.setBelong(key);

            SysDictData dict =
                    belongList.stream().filter(item -> item.getDictValue().equals(key.toString())).findAny().orElse(null);
            publishVo.setBelongName(dict != null ? dict.getDictLabel() : "");
            value.sort(Comparator.comparing(Depart::getCount).reversed());
            publishVo.setDepartList(value);

            publishVos.add(publishVo);
        });


        return publishVos;
    }

    @Override
    public Integer countVisitByContentId(Long contentId){
        return statisticsMapper.countVisitByContentId(contentId);
    }

    @Override
    public List<StatisticsVO> exportStatistics(Statistics statistics) {
        List<StatisticsVO> vos = statisticsMapper.exportStatistics(statistics);

        SysDictData sysDictData = new SysDictData();
        sysDictData.setDictType("business_belong");
        List<SysDictData> belongList = dictDataService.selectDictDataList(sysDictData);

        vos.forEach(item -> {
            for (SysDictData dictData : belongList) {
                if (item.getContentBelong() != null && item.getContentBelong().toString().equals(dictData.getDictValue())) {
                    item.setContentBelongName(dictData.getDictLabel());
                }
                if (item.getStaffBelong() != null && item.getStaffBelong().toString().equals(dictData.getDictValue())) {
                    item.setStaffBelongName(dictData.getDictLabel());
                }
            }
        });

        return vos;
    }
}
